﻿#region NeoPatterns
// 
// NeoPatterns framework is released under LGPLv3 license.
// See http://www.opensource.org/licenses/lgpl-3.0.html for more details.
// 
// Please visit http://neopatterns.wikidot.com for more information about NeoPatterns
// 
// Copyright (c) Pascal Craponne 2008
// 
#endregion

using System;
using NeoPatterns.Core.Registry;
using NeoPatterns.Exception;
using NeoPatterns.Utility;

namespace NeoPatterns.Patterns.Proxy
{
    public static class ObjectDefinitionTransportExtension
    {
        private static readonly ProxyAdvisor proxyAdvisor = new ProxyAdvisor();

        /// <summary>
        /// Registers with target accessor
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objectDefinitionTransport"></param>
        /// <param name="objectName"></param>
        /// <param name="proxyObjectName">Object of type IProxy to be declared</param>
        public static void UnderProxy<T>(this ObjectDefinitionTransport<T> objectDefinitionTransport, string objectName, string proxyObjectName)
        {
            // a proxy is not allowed using this form for non-singleton objects
            if (objectDefinitionTransport.Instance)
                throw new ConsistencyException(objectName);

            // the object is registered with an advisor allowing the change target
            objectDefinitionTransport.WithAdvisor(Ref.ByObject(proxyAdvisor)).UnderName(objectName);
            // then, an accessor to proxy advisor is set
            objectDefinitionTransport.ObjectRegistry.RegisterDefinition(proxyObjectName, typeof(AspectProxy), null, objectDefinitionTransport.Instance,
                                                                     (Func<IObjectRegistry, object>)(objectRegistry =>
                                                                                                  new AspectProxy(objectRegistry.Get(objectName),
                                                                                                                   proxyAdvisor)),
                                                                     null);
        }
    }
}